<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      title="登录 / 注册"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- input表单 -->
    <van-form 
      ref="login-form"
      :show-error="false" 
      :show-error-message="false"
      :validate-first="true"
      @submit="onLogin" 
      @failed="onFailed"
    > 
      <van-field
        v-model="user.mobile"
        icon-prefix="iconfont icon"
        left-icon="shouji"
        name="mobile"
        placeholder="请输入手机号"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        class="vab_field_btn"
        clearable
        name="code"
        icon-prefix="iconfont icon"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="formRules.code"
      >
        <template
          #button
        >  
          <van-button
            v-if="isHidden"
            class="send-btn"
            size="small"
            round
            :loading="isSendmsg"
            @click.prevent="verification"
          >
            发送验证码
          </van-button>
          <!--  v-show="isHidden" -->
          <div 
            v-else
            class="timeS"
          >
            {{ retTime }}  s
          </div>
        </template>
      </van-field>
      <!-- 按钮 -->
      <div class="login-button">
        <van-button
          class="login-btn"
          type="info"
          block
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
	import  {login,sendSms}  from '../../api/user';
	import  {Toast , Form , Field }  from 'vant';
	export default {
		name: 'LoginIndex',
		components: {},
		data: () => {
			return {
				isHidden:true,//控制按钮和倒计时的开光
				isSendmsg:false,//加载样式
				retTime:60,
				name: '登录页面', //ttapi.research.itcast.cn/，
				user:{
					mobile: '13911111111',
				    code: '246810',
					},
				formRules:{
					mobile:[
						{required:true,message:'手机号不能为空'},
						{pattern:/^1\d{10}$/,message:'手机号格式不正确'},
					],
				    code:[
						{required:true,message:'验证码不能为空'},
						{pattern:/^\d{6}$/,message:'验证码格式不正确'},
					]	
				},
			}
		},
		computed: {},
		methods: {
			// 验证码
			 async verification(){
				 // 通过.then()来拿结果
				 //  this.$refs.['login-form'].validate('mobile').then(
					// data =>{
					// 	console.log(data)
					// })
					// console.log(this.user.mobile)
					try{
					 // 校验手机号码
					 await	this.$refs.['login-form'].validate('mobile')
					 this.isSendmsg = true
					 //验证通过，请求发送验证码
					 const phone = await sendSms(this.user.mobile)
					 // console.dir(phone)
					 //按钮消失，倒计时60s,到0时恢复
					 this.isHidden=!this.isHidden
					 var setIntTime = setInterval(()=>{
					    this.retTime--
						console.log(this.retTime)
						if(this.retTime==0){
							 clearInterval(setIntTime)
							 this.isHidden=!this.isHidden
							 this.retTime=60
						}
					 },1000)
					}catch(err){
						// try里面任何代码的错误都会进入catch
						//不同的代码需要不同的提示，那就需要判断了
						let message=''
						if(err && err.response && err.response.status == 429){
							//发送短信失败的错误提示
							message = '发送太频繁了，请稍后重试'
						}else if(err.name === 'mobile'){
							//表单验证失败的错误提示
							message = err.message
						}else{
							//未知错误
							message = '发送失败，请稍后重试'
						}
						console.dir(err)
						Toast({
							message,
							position:'top'
						})
					}
					this.isSendmsg = false
				// this.$refs.['login-form'].validate('mobile')	
			},
			// 验证提示
			onFailed(error){
				// console.log(error)
				// console.log(error.errors[0].message)//获取验证失败的message
				// console.log(error.errors[0].name)
				Toast({
					message:error.errors[0].message,
					position:'top'
				})
				
			},
			// 发送请求
		    async onLogin () {
			  Toast.loading({
			  	message:'加载中...',//展示文本
			  	forbidClick:true,//禁止背景点击
				duration:0,//展示时长，为0时，toast不会消失
			  })
				// 1．找到数据接口
				// 2．封装请求方法
				// 3．请求调用登录
				try {
				    const res = await login(this.user)
					//4．处理响应结果
				    console.log('登录成功', res)
					Toast.success('登录成功！')
					
					//将后端返回的用户登录状态（token）放到Vuex容器中
					// this.$store.commit('setUser')
					this.$store.commit("setUser",res.data.data);
					//清除layout 的缓存，让它重新渲染
					this.$store.commit('removeCachePage','LayoutIndex')
				    //登录成功，跳转回原来页面
					// this.$router.back() 
					this.$router.push(this.$route.query.redirect || '/')
				  } catch (err) {
				    if (err.response.status === 400) {
				      console.log('登录失败', err)
					  Toast.fail('登录失败！')
				    }
				  }
				}
				
			},
	}
</script>
<style lang="less">
		.login-button{
			padding: 26px 16px;
		}
		.login-btn{
			border-radius: 8px;
			background-color: #6db4fb;
			border: 0.02667rem solid #6db4fb;
		}

	    .van-field__button{
			width: 76px !important;
			height: 23px !important;
			border-left: 1px solid #ededed !important;
			line-height: 10px !important;
		}
		.send-btn{
			width: 76px;
			height: 23px;
			background-color: #ededed;
			color: #666666;
			font-size: 10px;
		}
		// 修改toast的width
		.van-toast__text{
			width:300px !important;
		}
		// 验证时间
		.timeS{
			text-align: center;
			line-height: 18px;
			color: #a19c9c;
		}
</style>
